package news.dao;

import news.mdel.New;
import util.JdbcUtil;
import util.PageModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class NewDaoImpl implements NewDao{

    @Override
    public int saveOne(New new1) {
        String sql = "insert into news values(null,?,now(),?,?)";
        return JdbcUtil.editBySql(sql,new1.getTitle(), new1.getCategory(), new1.getContent());
    }

    @Override
    public New selectById(Integer newId) {
        String sql = "select title,date_format(createtime,'%Y-%m-%d %H:%i:%s') createtime,category,content" + " from news where newid = ?";
        List<Map<String,Object>> list = JdbcUtil.selectBySql(sql,newId);
        Map<String,Object> map = list.get(0);
        String title = (String) map.get("title");
        String category = (String) map.get("category");
        String createtime = (String) map.get("createtime");
        String content = (String) map.get("content");
        New new1 = new New(newId,title,category,createtime,content);
        return new1;
    }

    @Override
    public List<New> selectByPage(PageModel pageModel){
        List<New> news = new ArrayList<>();
        String likeValue = pageModel.getLikeValue();
        StringBuffer sql = new StringBuffer("select newid,title,category,date_format(createtime,'%Y-%m-%d %H:%i:%s') createtime" + " from news where title like ?");
        int recordCount = JdbcUtil.selectBySql(sql.toString(),"%"+likeValue+"%").size();
        pageModel.setRecordCount(recordCount);
        sql.append(" order by createtime desc limit ?,?");
        int startNo = (pageModel.getPageNo()-1)* pageModel.getPageSize();
        List<Map<String, Object>> list = null;
        list = JdbcUtil.selectBySql(sql.toString(),"%"+likeValue+"%",startNo,pageModel.getPageSize());
        for (int i = 0; i < list.size(); i++){
            Map<String,Object> map = list.get(i);
            Integer newid = (Integer) map.get("newid") ;
            String title = (String) map.get("title");
            String createtime = (String) map.get("createtime");
            String category = (String) map.get("category");
            news.add(new New(newid,title,category,createtime));
        }

        return news;

    }

    @Override
    public int deleteOne(Integer newid) {
        String sql = "delete from news where newid=?";
        int result = 0;
        result = JdbcUtil.editBySql(sql,newid);
        return result;
    }

    ;
}
